const Chat = {
  state: {
    chatIdList: [],   // 点击的用户ChatId
    unReadMsgList: [],  // 未读数据num，给chat页面用
    receiveMsgList: [],  // 接收到的聊天数据
  },
  mutations: {
    // 点击的用户ChatId
    setChatIdList(state, chatIdList) {
      state.chatIdList = chatIdList
    },

    // 在线时接收到新数据
    updateMsgList(state, payload) {

      console.log('在线时接收到新数据', payload)
      // receiveMsgList接收消息，chatContent页面用
      state.receiveMsgList.splice(0,state.receiveMsgList.length);
      state.receiveMsgList.push(payload)

      // 更新或新增unReadMsgList数据，更新chat页面数据
      let {chatId, time, msg, type} = payload;

      if (type === 'img') {
        msg = '[img]'
      } else if (type === 'file') {
        msg = '[file]'
      }

      let index = state.unReadMsgList.findIndex(item => item.name === chatId);
      if (index === -1) {
        state.unReadMsgList.push({
          name: chatId,
          num: 1,
          time: time,
          msg: msg
        })
      } else {
        state.unReadMsgList.splice(index, 1, {
          name: chatId,
          num: state.unReadMsgList[index].num + 1,
          time: time,
          msg: msg
        })
      }

      // 在本地保存的未读消息记录
      let localUnReadMsg = JSON.parse(localStorage.getItem('unReadMsg') || '[]');
      let index2 = localUnReadMsg.findIndex(item => item.name === chatId);
      if ( index2 === -1 ) {
        localUnReadMsg.push(...state.unReadMsgList)
      } else {
        localUnReadMsg.splice(index, 1, ...state.unReadMsgList)
      }
      localStorage.setItem('unReadMsg', JSON.stringify(localUnReadMsg))
    },

    deleteReadMsg(state){
      // 清空接收到的消息
      state.receiveMsgList.splice(0,state.receiveMsgList.length);


      // 删除unReadMsgList保存的未读消息，更新chat页面数据
      let index = state.unReadMsgList.findIndex(item => item.name === state.chatIdList.name);
      if ( index !== -1 ) {
        state.unReadMsgList.splice(index, 1)
      }

      // 删除本地保存的未读消息记录
      let localUnReadMsg = JSON.parse(localStorage.getItem('unReadMsg') || '[]');
      let index2 = localUnReadMsg.findIndex(item => item.name === state.chatIdList.name);
      if ( index2 !== -1 ) {
        localUnReadMsg.splice(index2, 1)
      }
      localStorage.setItem('unReadMsg', JSON.stringify(localUnReadMsg));
    }

  },
  actions: {


  },
};
export default Chat;
